package com.ht.modules.system.service.impl;

import com.ht.modules.system.entity.SysUser;
import com.ht.modules.system.service.IAppPushMessageService;
import com.ht.modules.system.service.ISysUserService;
import com.ht.utils.AppPushUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class AppPushMessageServiceImpl implements IAppPushMessageService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public void applyPassNotifySupplier(String supplierId, String applyTypeName) {
        SysUser sysUser = sysUserService.getById(supplierId);
        String cid = sysUser.getCid();
        if (Strings.isEmpty(cid)) {
            log.error("【审批流通过通知】失败，未找cid：用户id为 " + supplierId);
        }
        AppPushUtil.pushMessageToSingle("审批通过通知", "您有一条" + applyTypeName + "的审批已通过", cid);
    }

    @Override
    public void pushMsg(String title, String content, String roleCode1, String... otherRoleCodes) {
        List<String> cids = this.getCidsByRoleCodes(roleCode1, otherRoleCodes);
        AppPushUtil.pushMessageToList(title, content, cids);
    }

    // ————————————————————————————————私有方法——————————————————————————————————
    private List<String> getCidsByRoleCodes(String roleCode1, String... roleCodes) {
        List<String> cidList = new ArrayList<>();
        List<String> roleCodeList = new ArrayList<>();
        roleCodeList.add(roleCode1);
        roleCodeList.addAll(Arrays.asList(roleCodes));

        for (String roleCode : roleCodeList) {
            List<SysUser> users = sysUserService.listUserByRoleCode(roleCode);
            for (SysUser user : users) {
                if (Strings.isEmpty(user.getCid())) {
                    log.error("【APP通知】失败，未找cid：" + user.getRealname());
                    continue;
                }
                if (cidList.contains(user.getCid())) {
                    continue;
                }
                cidList.add(user.getCid());
            }
        }
        return cidList;
    }
}
